package cn.edu.lingnan.util;

import org.xml.sax.SAXException;

import javax.xml.transform.stream.StreamSource;
import javax.xml.validation.Schema;
import javax.xml.validation.SchemaFactory;
import javax.xml.validation.Validator;
import java.io.File;
import java.io.IOException;

public class XmIValidator {
    //功能：使用XSD文件来验证XML文件的有效性
    //输入参数：这两个文件的文件名；输出参数：是否有效，验证成功或失败
    public static boolean validate(String _vmlFileName,String _xsdFileName){
        boolean flag = false;
        try {
            //创建模式工厂 SchemaFactory
            SchemaFactory schemaFactory = SchemaFactory.newInstance(
                    "http://www.w3.org/2001/XMLSchema");

            //通过XSD文件创建模式Schema
            File file = new File(_xsdFileName);
            Schema schema = schemaFactory.newSchema(file);

            //由模式创建验证器Validator
            Validator validator = schema.newValidator();

            //使用验证器验证XML文件
            StreamSource streamSource = new StreamSource(_vmlFileName);
            validator.validate(streamSource);
            flag=true;

        } catch (SAXException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            System.out.println("[Debug] XML 文件在验证时出错........");
            throw new RuntimeException(e);
        }


        return flag;
    }
}
